Control Flow
if Statement
if condition {
// code if condition is true
} else if anotherCondition {
// code if anotherCondition is true
} else {
// code if no condition is true
}
- No parentheses
()around the condition (unlike C/Java). - The braces
{}are mandatory even for single-line statements. - You can have an optional initialization statement before the condition.
for Loop
Go has only one loop keyword: for.
Classic for-loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
While-like loop
i := 0
for i < 5 {
fmt.Println(i)
i++
}
Infinite loop
for {
fmt.Println("Forever...")
break // must break manually
}
Range loop
nums := []int{10, 20, 30}
for index, value := range nums {
fmt.Println(index, value)
}
switch Statement
switch variable {
case value1:
// code
case value2:
// code
default:
// code
}
Key Features in Go’s switch:
- No break needed — it automatically stops after a match.
- Multiple values per case:
switch day {
case 1, 2, 3:
fmt.Println("Early week")
} - Switch without an expression (acts like
if-elsechain):num := 10
switch {
case num < 0:
fmt.Println("Negative")
case num == 0:
fmt.Println("Zero")
default:
fmt.Println("Positive")
}